package com.risk.ctrl.config.okhttp.interceptor;

import com.risk.ctrl.entity.property.CreditProperty;
import com.risk.ctrl.utils.Java8DateUtils;
import com.risk.ctrl.utils.Md5Utils;
import com.risk.ctrl.utils.StringBulidUtils;
import lombok.RequiredArgsConstructor;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RequiredArgsConstructor
public class HeaderInterceptor implements Interceptor {

    private final CreditProperty creditProperty;

    private final String SIGNATURE = "appid={appId}&ctime={ctime}&{token}";
    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request original = chain.request();
        Long time = System.currentTimeMillis();
        Request request = original.newBuilder()
                .header("sign", getSignature(time))
                .header("appid", creditProperty.getAppId())
                .header("ctime", time.toString())
                .method(original.method(), original.body())
                .build();
        return chain.proceed(request);
    }

    private String getSignature(Long  time) {
        return Md5Utils.md52Hex(StringBulidUtils.replaceAllBrace(SIGNATURE, creditProperty.getAppId(), time, creditProperty.getToken()));
    }
}
